#图片验证码校验序列化器
from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers
import logging

logger = logging.getLogger('django')
#
class ImageCodeCheckSerializer(serializers.Serializer):
#     """
#     图片验证码校验序列化器
#     前段传入 --> 存入数据库 --> 返回响应
#     image_code_id:是uuid生成的编号
#     text：是验证码内容
#     """
#     #
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4,min_length=4)

    def validate(self, attrs):
        """校验"""
        image_code_id = attrs['image_code_id']
        text = attrs['text']

        #获取redis的对象
        redis_conn = get_redis_connection('verify_codes')
        #获取redis中的图片验证码,并判断是否存在
        redis_conn_text = redis_conn.get('img_%s'%image_code_id)
        if redis_conn_text is None:
            raise serializers.ValidationError('验证码无效')
        #删除图片验证码
        try:
            redis_conn.delete('img_%s'%image_code_id)
        except RedisError as e:
            logger.error(e)
        #比较图片验证码
        redis_conn_text = redis_conn_text.decode()
        if redis_conn_text.lower() != text.lower():
            raise serializers.ValidationError('验证码错误')
        #判断是否超过60秒 
        mobile = self.context['view'].kwargs['mobile']
        send_flg = redis_conn.get('send_flg_%s'%mobile)
        if send_flg:
            raise serializers.ValidationError('短信发送频繁')
        return attrs

